#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Desc    :   空运单号蜘蛛基类
"""

import copy
from typing import Union, Dict

from src.enum.task import CrawlerTypeEnum
from src.exception import WaybillNumberInvalidException, WebpageLoadingErrorException, CrawlerException
from src.model.air_waybill import AwbResult
from src.util import flogger
from parsel import Selector

class AwbSpiderBase:
    """空运单解析器"""
    key: str = None

    log = flogger.Flogger().get_logger(__name__)

    def format_awb_num(self,awb_num: str):
        """格式化运单号

        Args:
            awb_num (str): 传入的运单号

        Returns:
            str: 格式后的运单号，XXX-XXXXXXXX
        """
        t_waybill_num = copy.deepcopy(awb_num)
        if len(t_waybill_num) == 11:
            t_waybill_num = awb_num[0:3] + "-" + awb_num[3:11]
        return t_waybill_num

    def crawling_page(self,waybills: str,proxy=None,idx: int = 0) -> Union[None, Dict, Selector]:
        return None

    def check_waybill_num(self, waybill_num: str) -> bool:
        return waybill_num.startswith(self.key)

    def pick_base_info(self, data) -> AwbResult | None:
        return None

    def convert_result(self, data) -> AwbResult:
        awb_info = self.pick_base_info(data)
        return awb_info

    def run(self, awb_num: str) -> AwbResult:
        if not self.check_waybill_num(awb_num):
            raise WaybillNumberInvalidException()
        t_waybill_num = self.format_awb_num(awb_num)
        self.log.info(f"{CrawlerTypeEnum.AIR_WAYBILL.name} crawler number: {awb_num}({self.key}) run begin!")
        try:
            page_data = self.crawling_page(t_waybill_num)
        except CrawlerException as e:
            raise e
        except Exception as e:
            self.log.error(e)
            raise WebpageLoadingErrorException()
        return self.convert_result(page_data)

